from fastapi import FastAPI, APIRouter
from pydantic import BaseModel
from database import db
from sqlalchemy.future import select
from typing import Optional
router = APIRouter()

class Admin(BaseModel):
    username: str
    password: str

class User(BaseModel):
    name: str
    num:str
    sf:str
@router.post('/login')
async def login(admin: Admin):
    num=admin.username
    pwd=admin.password
    try:
        exit=await db.Admin.filter(num=num,pwd=pwd)
    except:
        return {
            'code': 404,
            'msg': 'fail'
        }
    if exit:
        return{
            'code' : 200,
            'msg' : 'success'
        }
    else:
        return {
            'code' : 404,
            'msg' : 'fail'
        }
#查询用户有关信息

@router.get('/get_users')
async def get_users(sf: Optional[str]=None,num :Optional[str]=None):
    if num is None:
        users = await db.User.filter(sf=sf)
    else:
        users=await db.User.filter(num=num).values()
    return {
        'code': 200,
        'msg': users,
    }

#查询班级有关信息
@router.get('/get_class')
async def get_class(name: Optional[str]=None):
    if name is None:
        all_classes = await db.Class.all().values()
        return {
            'code' : 200,
            'msg': all_classes
        }
    else:
        class_=await db.Class.filter(name=name).values()
        return {
            'code' : 200,
            'msg': class_
        }

#查询课程有关信息
@router.get('/get_course')
async def get_course(name: Optional[str]=None):
    if name is None:
        all_courses = await db.Course.all().values()
        return {
            'code' : 200,
            'msg': all_courses
        }
    else:
        course=await db.Course.filter(name=name).values()
        return {
            'code' : 200,
            'msg': course
        }

#添加用户信息
@router.post('/add_user')
async def add_user(user: User):
    name=user.name
    num=user.num
    sf=user.sf
    exit=await db.User.filter(num=num)
    if exit:
        return{
            'code': 400,
            'msg': '该账号已存在'
        }
    else:
        new_user=await db.User.create(name=name,num=num,sf=sf)
        return {
            'code': 200,
            'msg': 'success',
        }

#添加班级信息
@router.post('/add_class')
async def add_class(name: str):
    exit=await db.Class.filter(name=name)
    if exit:
        return {
            'code': 400,
            'msg': 'fail'
        }
    new_class = await db.Class.create(name=name)
    return {
        'code': 200,
        'msg': 'success'
    }

#添加课程信息
@router.post('/add_course')
async def add_course(name: str):
    exit=await db.Course.filter(name=name)
    if exit:
        return {
            'code': 400,
            'msg': 'fail'
        }
    new_course = await db.Course.create(name=name)
    return {
        'code': 200,
        'msg': 'success'
    }